package com.zby.demo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author ChrisPhantom
 * @CreateDate 2020/12/13 23:08
 */
@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    private String[] pathList;

    public void destroy() {
        System.out.println("LoginFilter已结束");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        String requestPath = request.getServletPath();
        if (containsPath(requestPath) || session.getAttribute("LoginUser") != null) {
            if (session.getAttribute("LoginUser") != null) {
                String classify = (String) session.getAttribute("classify");
                if (requestPath.contains("/front/" + classify) || (classify.equals("administrator") && requestPath.contains("/back"))) {
                    chain.doFilter(req, resp);
                } else {
                    String url = "/studentmanage";
                    if (classify.equals("administrator")) {
                        url += "/back";
                    } else {
                        url += "/front/" + classify;
                    }
                    response.sendRedirect(url);
                }
            } else {
                chain.doFilter(req, resp);
            }
        } else {
            response.sendRedirect("/studentmanage/index.html");
        }
    }

    public boolean containsPath(String path) {
        for (String p : pathList) {
            if (p.equals(path)) {
                return true;
            }
        }
        return false;
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("LoginFilter已运行");
        String values = config.getInitParameter("paths");
        pathList = values.split(",");
    }
}
